// FontDoc.cpp : implementation file
//

#include "stdafx.h"
#include "U7FileTool.h"
#include "FontDoc.h"

#include "U7FileDefs.h"
#include "Shape.h"

// CFontDoc

IMPLEMENT_DYNCREATE(CFontDoc, CDocument)

CFontDoc::CFontDoc()
{
	m_pFontFile = NULL;
}

BOOL CFontDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument())
		return FALSE;
	return TRUE;
}

CFontDoc::~CFontDoc()
{
	if ( m_pFontFile )
		delete [] m_pFontFile;
}


BEGIN_MESSAGE_MAP(CFontDoc, CDocument)
END_MESSAGE_MAP()


// CFontDoc diagnostics

#ifdef _DEBUG
void CFontDoc::AssertValid() const
{
	CDocument::AssertValid();
}

#ifndef _WIN32_WCE
void CFontDoc::Dump(CDumpContext& dc) const
{
	CDocument::Dump(dc);
}
#endif
#endif //_DEBUG

#ifndef _WIN32_WCE
// CFontDoc serialization

void CFontDoc::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		// TODO: add storing code here
	}
	else
	{
		// TODO: add loading code here
		CFile* pFile = ar.GetFile();
		LONG lLength = (LONG)pFile->GetLength();

		m_pFontFile = new BYTE[lLength];
		if ( !m_pFontFile )
			AfxThrowMemoryException();

		if ( lLength != pFile->Read( m_pFontFile, lLength ) )
			AfxThrowFileException(CFileException::genericException,100);
	}
}
#endif


// CFontDoc commands


void CFontDoc::DeleteContents()
{
	// TODO: Add your specialized code here and/or call the base class
	if ( m_pFontFile )
	{
		delete [] m_pFontFile;
		m_pFontFile = NULL;
	}

	CDocument::DeleteContents();
}

CSize CFontDoc::GetDocSize()
{
	PFLEXFILEHEADER header = (PFLEXFILEHEADER)m_pFontFile;
	int nShapeCount = header->count;
	int nMaxHeight = 0;
	int nMaxWidth = 0;

	for ( int i = 0; i < nShapeCount; i ++ )
	{
		long shapeLength;
		PSHAPEENTRY shapeEntry = GetShape( (const char*)m_pFontFile, i, shapeLength );
		int nFrameCount = GetShapeFrameCount( shapeEntry, shapeLength );
		int nWidth = 0;
		int nHeight = 0;

		for ( int j = 0; j < nFrameCount; j++ )
		{
			POINT hotspot;
			SIZE size;
			GetShapeFrameInfo( shapeEntry, shapeLength, j, hotspot, size );
			if ( size.cy > nHeight )
				nHeight = size.cy;
			nWidth += size.cx;
		}

		if ( nWidth > nMaxWidth )
			nMaxWidth = nWidth;

		nMaxHeight += nHeight;

		//TRACE( "%2d (%d): Width:%d, Height:%d\n", i, nFrameCount, nWidth, nHeight );
	}

	return CSize(nMaxWidth,nMaxHeight);
}
